#include "task.h"

static task_t *tasks[MAX_TASKS];
static int taskLen = 0;
static int currentTask = -1;

void add_task(task_t *t) {
    if(taskLen >= MAX_TASKS) return;
    tasks[taskLen++] = t;
}

task_t* schedule_task(isr_registers_t *reg) {
    if(taskLen == 0) return 0;
    if(currentTask >= 0) {
        uint32_t *esp = (uint32_t *)tasks[currentTask];
        *esp = (uint32_t) reg;
    }
    if(++currentTask >= taskLen) currentTask %= taskLen;
    return tasks[currentTask];
}

void init_task(task_t *t, task_callback callback) {
    uint8_t *p = (uint8_t *) t;
    isr_registers_t *r = (isr_registers_t *)(p + STACK_SIZE - sizeof(isr_registers_t));
    uint32_t *esp = (uint32_t *)p;
    *esp = (uint32_t)r;
    r->ds = 0x10;
    r->edi = 0;
    r->esi = 0;
    r->ebp = (uint32_t) (p + STACK_SIZE);
    r->useless = 0;
    r->ebx = 0;
    r->edx = 0;
    r->ecx = 0;
    r->eax = 0;
    r->int_no = 0;
    r->error_code = 0;
    r->eip = (uint32_t) callback;
    r->cs = 0x08;
    r->eflags = 0x00000202; // 第9位(从0开始)置1以允许中断
    // r->esp = (uint32_t)(p + STACK_SIZE - sizeof(uint32_t));
    r->esp = 0;
    r->ss = 0x10;
}
